{% extends 'base.html' %}
{% load staticfiles %}

{% block head %}
    <link rel="stylesheet" href="{% static 'AdminLTE/bower_components/select2/dist/css/select2.min.css' %}">
    <link rel="stylesheet" href="{% static 'jquery-confirm/dist/jquery-confirm.min.css' %}">
    <link rel="stylesheet" href="{% static 'modaal/css/modaal.min.css' %}">
    <link rel="stylesheet" href="{% static 'css/selectize.css' %}">
    <style>
        .col-sm-10 {
            width: 40%;
        }

        .has-select-error {
            border: 1px solid red;
        }
    </style>
{% endblock %}

{% block content-header %}
    <h1>资产信息</h1>
{% endblock %}

{% block content %}
    <div id="ip_select_form" style="display:none;">
        <div class="col-xs-12">
            <div class="box no-border no-shadow">
                <div class="box-header">
                    <h3 class="box-title">请选择IP地址</h3>
                </div>
                <div class="box-body">
                    <form class="form-horizontal" style="margin-top: 20px;">
                        <div class="form-group">
                            <label for="IP_segment" class="col-sm-2 control-label">IP网段</label>
                            <div class="col-sm-9">
                                <select name="IP_segment" id="IP_segment" style="display: none;">
                                </select>
                            </div>
                        </div>
                        <div class="form-group">
                            <label for="IP_state" class="col-sm-2 control-label">IP状态</label>
                            <div class="col-sm-9">
                                <select style="display: none;" name="IP_state" id="IP_state">
                                    <option value="0">空闲</option>
                                    <option value="1">占用</option>
                                </select>
                            </div>
                        </div>
                        <div class="form-group">
                            <label for="IP" class="col-sm-2 control-label">IP地址</label>
                            <div class="col-sm-9">
                                <select name="IP" id="IP" style="display: none;">
                                </select>
                            </div>
                        </div>
                    </form>
                </div>
                <div class="box-footer no-border">
                    <div class="pull-right">
                        <button type="button" class="btn btn-default" onclick="$('#ip_select').modaal('close');">关闭</button>&nbsp;&nbsp;&nbsp;&nbsp;
                        <button type="button" class="btn btn-info" onclick="confirmIPSelect();">确认</button>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <form class="form-horizontal" id="update_asset">
        <div class="box-body">
            <div class="form-group">
                <label for="asset_type" class="col-sm-2 control-label">资产类型</label>
                <div class="col-sm-10">
                    {% for asset_type in asset_types %}
                        {% if asset.asset_type == asset_type.0 %}
                            <select class="form-control select2" id="asset_type" name="asset_type" disabled="disabled"
                                    style="width: 100%;">
                                <option value="{{ asset_type.0 }}">{{ asset_type.1 }}</option>
                            </select>
                        {% endif %}
                    {% endfor %}
                </div>
            </div>

            <div class="form-group">
                <label for="device_type" class="col-sm-2 control-label">设备类型</label>
                <div class="col-sm-10">
                    {% if asset.asset_type == 'server' %}
                        <select class="form-control select2" id="device_type" name="device_type" disabled="disabled"
                                style="width: 100%;">
                            <option value="{{ asset.serverassets.id }}">{{ asset.serverassets.get_server_type_display }}</option>
                        </select>
                    {% elif asset.asset_type == 'network' %}
                        <select class="form-control select2" id="device_type" name="device_type" disabled="disabled"
                                style="width: 100%;">
                            <option value="{{ asset.networkassets.id }}">{{ asset.networkassets.get_network_type_display }}</option>
                        </select>
                    {% elif asset.asset_type == 'office' %}
                        <select class="form-control select2" id="device_type" name="device_type" disabled="disabled"
                                style="width: 100%;">
                            <option value="{{ asset.officeassets.id }}">{{ asset.officeassets.get_office_type_display }}</option>
                        </select>
                    {% elif asset.asset_type == 'security' %}
                        <select class="form-control select2" id="device_type" name="device_type" disabled="disabled"
                                style="width: 100%;">
                            <option value="{{ asset.securityassets.id }}">{{ asset.securityassets.get_security_type_display }}</option>
                        </select>
                    {% elif asset.asset_type == 'storage' %}
                        <select class="form-control select2" id="device_type" name="device_type" disabled="disabled"
                                style="width: 100%;">
                            <option value="{{ asset.storageassets.id }}">{{ asset.storageassets.get_storage_type_display }}</option>
                        </select>
                    {% elif asset.asset_type == 'software' %}
                        <select class="form-control select2" id="device_type" name="device_type" disabled="disabled"
                                style="width: 100%;">
                            <option value="{{ asset.softwareassets.id }}">{{ asset.softwareassets.get_software_type_display }}</option>
                        </select>
                    {% endif %}
                </div>
            </div>

            {% if asset.serverassets.server_type == 1 %}
                <div class="form-group hosted_on">
                    <label for="hosted_on" class="col-sm-2 control-label">宿主机</label>
                    <div class="col-sm-10">
                        <select class="form-control" id="hosted_on" name="hosted_on">
                            </select>
                    </div>
                </div>
            {% endif %}

            <div class="form-group">
                <label for="asset_nu" class="col-sm-2 control-label">资产编号/资产名称</label>
                <div class="col-sm-10">
                    <input type="text" class="form-control" name="asset_nu" id="asset_nu"
                           value="{{ asset.asset_nu }}" readonly>
                </div>
            </div>

            {% if asset.asset_type == 'server' %}
            <div class="form-group">
                <label for="asset_product" class="col-sm-2 control-label">产品名称</label>
                <div class="col-sm-10">
                    <select style="display: none;" name="asset_product" id="asset_product" value="{{ asset.asset_product_id| default:'' }}">
                        <option value="{{ asset.asset_product_id| default:'' }}">{{ asset.asset_product.product_name }}</option>
                    </select>
                </div>
            </div>
            {% endif %}

            <div class="form-group">
                <label for="asset_status" class="col-sm-2 control-label">设备状态</label>
                <div class="col-sm-10">
                    <select class="form-control" name="asset_status" id="asset_status">
                        {% for asset_status in asset_status_ %}
                            {% if asset_status.0 == asset.asset_status %}
                                <option value="{{ asset_status.0 }}"
                                        selected>{{ asset_status.1 }}</option>
                            {% else %}
                                <option value="{{ asset_status.0 }}">{{ asset_status.1 }}</option>
                            {% endif %}
                        {% endfor %}
                    </select>
                </div>
            </div>

            <div class="form-group">
                <label for="asset_management_ip" class="col-sm-2 control-label">管理IP{% if asset.asset_type == 'server' %}<span class="text-red">*</span>{% endif %}</label>
                <div class="col-sm-10">
                    <div class="input-group">
                        <input name="asset_management_ip" id="asset_management_ip" value="{{ asset.asset_management_ip.id }}" style="display: none;">
                        <input class="form-control" id="asset_management_ip_value" value="{{ asset.asset_management_ip.IP }}" readonly>
                        <a type="button" class="input-group-addon btn btn-primary" id="ip_select" data-modaal-type="inline" data-modaal-animation="fade" onclick="assetIpSelect();">选择</a>
                    </div>
                </div>
            </div>

            <!--div class="form-group">
                <label for="asset_admin" class="col-sm-2 control-label">资产管理员</label>
                <div class="col-sm-10">
                    <select class="form-control" name="asset_admin" id="asset_admin">
                        {% for asset_admin in asset_admins %}
                            {% if asset_admin.id == asset.asset_admin.id %}
                                <option value="{{ asset_admin.id }}"
                                        selected>{{ asset_admin.username }}</option>
                            {% else %}
                                <option value="{{ asset_admin.id }}">{{ asset_admin.username }}</option>
                            {% endif %}
                        {% endfor %}
                    </select>
                </div>
            </div-->

            <div class="form-group">
                <label for="asset_environment" class="col-sm-2 control-label">设备环境<span class="text-red">*</span></label>
                <div class="col-sm-10">
                    <select class="form-control" name="asset_environment" id="asset_environment">
                        {% for asset_environment in asset_environment_ %}
                            <!--option value="{{ asset_environment.0 }}" {% if asset_environment.0|stringformat:"s" == asset.asset_environment %} selected="selected" {% endif %}>{{ asset_environment.1 }}</option-->
                            <option value="{{ asset_environment.0 }}" {% if asset_environment.0 == asset.asset_environment %} selected="selected" {% endif %}>{{ asset_environment.1 }}</option>
                        {% endfor %}
                    </select>
                </div>
            </div>

            <div class="form-group">
                <label for="asset_memo" class="col-sm-2 control-label">备注</label>
                <div class="col-sm-10">
                    <textarea class="form-control" name="asset_memo" id="asset_memo">{{ asset.asset_memo }}</textarea>
                </div>
            </div>

            {% if asset.asset_type == 'server' %}
            <div class="form-group">
                <label for="asset_applicant" class="col-sm-2 control-label">申请人</label>
                <div class="col-sm-10">
                    <input type="text" class="form-control" name="asset_applicant" id="asset_applicant" value="{{ asset.asset_applicant| default_if_none:"" }}">
                </div>
            </div>
            <div class="form-group">
                <label for="asset_runner" class="col-sm-2 control-label">负责人</label>
                <div class="col-sm-10">
                    <input type="text" class="form-control" name="asset_runner" id="asset_runner" value="{{ asset.asset_runner| default_if_none:"" }}">
                </div>
            </div>
            {% endif %}

            <div class="form-group">
                <label for="asset_purchase_day" class="col-sm-2 control-label">申请/购买日期<span
                        class="text-red">*</span></label>
                <div class="col-sm-10">
                    <input type="date" class="form-control" name="asset_purchase_day"
                           id="asset_purchase_day" value="{{ asset.asset_purchase_day|date:"Y-m-d" }}">
                </div>
            </div>

            <div class="form-group">
                <label for="asset_expire_day" class="col-sm-2 control-label">到期/过保日期<span class="text-red">*</span></label>
                <div class="col-sm-10">
                    <input type="date" class="form-control" name="asset_expire_day"
                           id="asset_expire_day" value="{{ asset.asset_expire_day|date:"Y-m-d" }}">
                </div>
            </div>
            {% if asset.asset_type != 'server' or asset.serverassets.server_type != 1 %}
            <div class="form-group">
                <label for="asset_provider" class="col-sm-2 control-label">供应商</label>
                <div class="col-sm-10">
                    <select class="form-control" name="asset_provider" id="asset_provider">
                        {% for asset_provider in asset_providers %}
                            {% if asset_provider.id == asset.asset_provider.id %}
                                <option value="{{ asset_provider.id }}"
                                        selected>{{ asset_provider.asset_provider_name }}</option>
                            {% else %}
                                <option value="{{ asset_provider.id }}">{{ asset_provider.asset_provider_name }}</option>
                            {% endif %}

                        {% endfor %}
                    </select>
                </div>
            </div>

            <div class="form-group">
                <label for="asset_model" class="col-sm-2 control-label">资产型号</label>
                <div class="col-sm-10">
                    <input type="text" class="form-control" name="asset_model" id="asset_model"
                           value="{{ asset.asset_model }}">
                </div>
            </div>

            <div class="form-group">
                <label for="asset_price" class="col-sm-2 control-label">价格（万元）</label>
                <div class="col-sm-10">
                    <input type="text" class="form-control" name="asset_price" id="asset_price"
                           value="{{ asset.asset_price }}">
                </div>
            </div>
            {% endif %}
            {% if asset.asset_type != 'server' or asset.serverassets.server_type == 0 %}
            <div class="form-group">
                <label for="asset_idc" class="col-sm-2 control-label">所在机房</label>
                <div class="col-sm-10">
                    <select class="form-control" name="asset_idc" id="asset_idc" onchange="idc()">
                        {% if asset.asset_idc %}
                            {% for asset_idc in asset_idcs %}
                                {% if asset_idc.id == asset.asset_idc.id %}
                                    <option value="{{ asset.asset_idc.id }}"
                                            selected>{{ asset.asset_idc.idc_name }}</option>
                                {% else %}
                                    <option value="{{ asset_idc.id }}">{{ asset_idc.idc_name }}</option>
                                {% endif %}
                            {% endfor %}
                        {% else %}
                            <option value=""></option>
                            {% for asset_idc in asset_idcs %}
                                <option value="{{ asset_idc.id }}">{{ asset_idc.idc_name }}</option>
                            {% endfor %}
                        {% endif %}
                    </select>
                </div>
            </div>

            <div class="form-group">
                <label for="asset_cabinet" class="col-sm-2 control-label">所在机柜</label>
                <div class="col-sm-10">
                    <select class="form-control" name="asset_cabinet" id="asset_cabinet">
                        {% if asset.asset_idc %}
                            {% for cabinet in asset.asset_idc.cabinet.all %}
                                {% if cabinet.id == asset.asset_cabinet_id %}
                                    <option value="{{ asset.asset_cabinet_id }}"
                                            selected>{{ asset.asset_cabinet.cabinet_name }}</option>
                                {% else %}
                                    <option value="{{ cabinet.id }}">{{ cabinet.cabinet_name }}</option>
                                {% endif %}
                            {% endfor %}
                        {% else %}
                            <option value=""></option>
                        {% endif %}
                    </select>
                </div>
            </div>
            {% endif %}

        </div>
        <!-- /.box-body -->

        <div class="box-footer">
            <button type="button" class="btn btn-default pull-right" onclick="history.go(-1)">返回</button>
            <button type="button" class="btn btn-info pull-right" onclick="updateAsset()">确认修改</button>
        </div>
        <!-- /.box-footer -->
    </form>
{% endblock %}

{% block js %}
    <!-- Select2 -->
    <script src="{% static 'AdminLTE/bower_components/select2/dist/js/select2.full.min.js' %}"></script>
    <script src="{% static 'jquery-confirm/dist/jquery-confirm.min.js' %}"></script>
    <script src="{% static 'modaal/js/modaal.min.js' %}"></script>
    <script src="{% static 'js/selectize.min.js' %}"></script>
    <script>
        $(function () {
            $('#asset_product').selectize({
                valueField: 'id',
                labelField: 'text',
                searchField: 'text',
                placeholder: '请输入搜索条件',
                load: function(query, callback) {
                    $.ajax({
                        url: '/project/find_product_name/',
                        data: {
                            product_name: query
                        },
                        dataType: 'json',
                        type: 'GET',
                        error: function() {
                            callback();
                        },
                        success: function(res) {
                            callback(res.results);
                        }
                    });
                }
            });

            $("#ip_select").modaal({
                width: 600,
                height: 360,
                content_source: '#ip_select_form',
            });
            $('.select2').select2();
            $('#hosted_on').select2({
                allowClear: true,
                ajax: {
                    url: '/assets/find_hosted_on',
                    dataType: 'json',
                    data: function (params) {
                        params.offset = 6
                        params.page = params.page || 1
                        var query = {
                            search: params.term,
                            page: params.page,
                            offset: params.offset,
                        }
                        return query;
                    },
                    processResults: function (data, params) {
                        var page = params.page || 1;
                        return {
                            results: data.results,
                            pagination: {
                              more: (page*params.offset) < data.total_count
                            }
                        };
                    },
                    cache: true
                  },
                minimumInputLength: 2,
                templateResult: formatRepo,
                templateSelection: formatRepoSelection,
                placeholder: '查询IP地址 或 项目编号/名称',
            });

            if('{{ asset.serverassets.hosted_on_id }}'!='None'){
                $('#hosted_on').append('<option value="{{ asset.serverassets.hosted_on_id }}" selected>{{ asset.serverassets.hosted_on.assets.asset_nu }}-{{ asset.serverassets.hosted_on.assets.asset_management_ip.IP }}</option>')
            }

            $('#IP_segment').selectize({
                valueField: 'id',
                labelField: 'text',
                searchField: 'text',
                onChange: function(value){
                    ipDetailSelect()
                }
            });
            $('#IP').selectize({
                valueField: 'id',
                labelField: 'text',
                searchField: 'text',
            });
            $('#IP_state').selectize({
                onChange: function(value){
                    ipDetailSelect()
                }
            })
        });

        function formatRepo (repo) {
                if (repo.loading) {
                    return repo.text;
                }
                var $container = $("<div class='select2-result-repository clearfix'>" +
                      "<div class='select2-result-repository-element'>" + repo.text +
                    "</div></div>");
                return $container;
            }

        function formatRepoSelection (repo) {
            return repo.text;
        }

        function assetIpSelect(){
            var IPSegmentSelect = $('#IP_segment')[0].selectize;
            IPSegmentSelect.clear()
            $.ajax({
                type: 'POST',
                url: '/assets/find_ip_segment/'
            }).then(function (data) {
                IPSegmentSelect.addOption(data.results)
            });
        }

        function ipDetailSelect(ipSegment,status){
            var ipSegment = $('#IP_segment').val()
            var ipstate = $('#IP_state').val()
            var IPSelect = $('#IP')[0].selectize
            IPSelect.clear()
            IPSelect.clearOptions()
            if(!ipSegment){
                return
            }
            $.ajax({
                type: 'POST',
                url: '/assets/find_ip/',
                data: {IP_segment: ipSegment, IP_state: ipstate},
            }).then(function (data) {
                IPSelect.addOption(data.results)
            });
        }

        function confirmIPSelect() {
            $(".modaal-container .selectize-input").removeClass('has-select-error').parent().parent().parent().removeClass('has-error').find('span').remove()
            if(!$('#IP_segment').val()){
                mes = '请选择IP网段'
                $('#IP_segment').parent().append('<span class="help-block">'+mes+'</span>').find('.selectize-input').addClass('has-select-error')
                $('#IP_segment').parent().parent().addClass('has-error')
            }
            if(!$('#IP_state').val()){
                mes = '请选择IP状态'
                $('#IP_state').parent().append('<span class="help-block">'+mes+'</span>').find('.selectize-input').addClass('has-select-error')
                $('#IP_state').parent().parent().addClass('has-error')
            }
            var IPSelect = $('#IP')
            var ip = IPSelect.val()
            var text = IPSelect.text()
            if(!ip){
                mes = '请选择IP地址'
                IPSelect.parent().append('<span class="help-block">'+mes+'</span>').find('.selectize-input').addClass('has-select-error')
                IPSelect.parent().parent().addClass('has-error')
                $.alert({
                        title: 'Tips',
                        type: 'red',
                        content: '请修改错误信息',
                    })
            } else {
                $('#asset_management_ip').val(ip)
                $('#asset_management_ip_value').val(text)
                $('#ip_select').modaal('close')
            }
        }

        function idc() {
            let idc_id = $('#asset_idc').val();
            let cabinet_obj = $('#asset_cabinet');
            $.ajax({
                url: '/api/idc/' + idc_id + '/',
                type: 'GET',
                success: function (res) {
                    let cabinets = res['cabinet'];
                    cabinet_obj.html('');
                    for (let i = 0; i < cabinets.length; i++) {
                        cabinet_obj.append(
                            '<option value=' + cabinets[i]['id'] + '>' + cabinets[i]['cabinet_name'] + '</option>'
                        )
                    }
                }
            })
        }

        (function ($) {
            $.fn.formatData = function (assetType) {
                let formatObj = {};
                let assetObj = {};
                let array = this.serializeArray();
                $(array).each(function () {
                    if (this.name.indexOf('asset_') !== -1) {
                        assetObj[this.name] = this.value;
                        formatObj['assets'] = assetObj;
                    } else if (this.name.indexOf('device_') !== -1) {
                        formatObj[assetType + '_type'] = this.value;
                    } else {
                        formatObj[this.name] = this.value;
                    }
                });
                return formatObj;
            };
        })(jQuery);

        function updateErrorMessage(errors) {
            $.each(errors, function(name, value){
                $.each(value, function(i, v){
                    $('#'+name).after('<span class="help-block">'+v+'</span>')
                })
                $('#'+name).parent().parent().addClass('has-error')
            })
        }

        function updateAsset() {
            {% if perms.assets.change_assets %}
                let assetType = $('#asset_type').val();
                let data = $('#update_asset').formatData(assetType);
                $('.help-block').remove()
                $('.form-group').removeClass('has-error')
                $('#asset_type+span,#device_type+span').removeClass('has-select-error')
                if($('#asset_type').val() == 'server'){
                    if($('#asset_management_ip').val() == ''){
                        mes = '管理IP不能为空'
                        $.alert({
                            title: 'Tips',
                            type: 'red',
                            content: mes,
                        })
                        updateErrorMessage({asset_management_ip:[mes]})
                        return
                    }
                }


                data.assets.id = {{ asset.id }}
                data.id = {% if asset.asset_type == 'server' %}
                        {{ asset.serverassets.id }}
                    {% elif asset.asset_type == 'network' %}
                        {{ asset.networkassets.id }}
                    {% elif asset.asset_type == 'office' %}
                        {{ asset.officeassets.id }}
                    {% elif asset.asset_type == 'security' %}
                        {{ asset.securityassets.id }}
                    {% elif asset.asset_type == 'storage' %}
                        {{ asset.storageassets.id }}
                    {% elif asset.asset_type == 'software' %}
                        {{ asset.softwareassets.id }}
                    {% endif %}
                if(data.hosted_on == 'None' || data.hosted_on == undefined){
                    data.hosted_on=''
                }
                $.ajax({
                    url: '/api/{{ asset.asset_type }}'+ '_assets/' +data.id +'/',
                    type: 'PUT',
                    {#data: JSON.stringify(data.assets),#}
                    data: JSON.stringify(data),
                    dataType: 'json',
                    contentType: "application/json",
                    success: function () {
                        $.confirm({
                                title: 'Tips',
                                content: '修改成功！',
                                type: 'green',
                                buttons: {
                                    Ok: function () {
                                        window.location.href = '{% url 'assets_list' %}';
                                    },
                                }
                            })
                    },
                    error: function (response) {
                        errors = JSON.parse(response.responseText)
                        if(errors.hasOwnProperty('detail')){
                            $.alert({
                                    title: 'Tips',
                                    type: 'red',
                                    content: errors.detail,
                                    buttons: {
                                                Ok: function () {
                                                    window.location.href = '/';
                                                },
                                            }
                                });
                            return
                        }
                        if(errors.hasOwnProperty('assets')){
                            assets_errors = errors.assets
                            if(assets_errors.hasOwnProperty('non_field_errors')){
                                var dateError = assets_errors.non_field_errors[0]
                                $.alert({
                                    title: 'Tips',
                                    type: 'red',
                                    content: dateError,
                                });
                                updateErrorMessage({asset_expire_day:[dateError]})
                            } else {
                                updateErrorMessage(assets_errors)
                                $.alert({
                                    title: 'Tips',
                                    type: 'red',
                                    content: '请修改错误信息',
                                });
                            }
                        }
                    }
                })
            {% else %}
                $.alert({
                    title: 'Tips',
                    type: 'red',
                    content: '抱歉！您没有修改资产的权限，如有问题请联系管理员！',
                    buttons: {
                                Ok: function () {
                                    window.location.href = '/';
                                },
                            }
                });
            {% endif %}
        }

    </script>
{% endblock %}





